package com.iot.modbus.event.subject;

import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.util.ReflectUtil;
import com.iot.modbus.event.MessageObserver;
import com.iot.modbus.event.pojo.DeviceMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MessageSubject {

    private static final List<MessageObserver> observers = new ArrayList<MessageObserver>();

    private static void init() {
        Class<MessageObserver> messageObserverClass = MessageObserver.class;
        Set<Class<?>> classes = ClassScanner.scanPackage("com.iot");
        classes.stream().filter(clazz ->
                messageObserverClass.isAssignableFrom(clazz) && !clazz.equals(messageObserverClass) && !clazz.isInterface()
        ).forEach(implementation -> {
            try {
                Object instance = ReflectUtil.newInstance(implementation); // 创建实例
                System.out.println("Created instance of: " + implementation.getName());
                if (instance instanceof MessageObserver) {
                    observers.add((MessageObserver) instance);
                }
            } catch (Exception e) {
                System.err.println("Failed to create instance of: " + implementation.getName());
            }
        });
    }

    public static void onMessage(DeviceMessage deviceMessage) {
        if (observers.isEmpty()){
            init();
        }
        for (MessageObserver observer : observers) {
            try {
                observer.onMessage(deviceMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
